<template>
  <div>
    <FormPanel ref="from" :list="formList" @formChange="changeHandle" :isSubmitBtn="false" :collapse="false" :labelWidth="190"></FormPanel>
    <FilterTable ref="table" :columns="columns" :dataSource="tableList" height="auto" :isSelectColumn="false" :onColumnsChange="columns => (this.columns = columns)">
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" @click="addHandle()" icon="el-icon-plus">新 增</multiuse-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="isaddCar" :title="'新增车辆'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <selectCar :dealerData="dealerData" @close="carcloseHandler" />
    </BaseDialog>

    <div style="height:47px;"></div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 2)" :disabled="ischange">提 交</multiuse-button>
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 3)" :disabled="ischange">保 存</multiuse-button>
      <el-button @click="closeDrawer(1)">关 闭</el-button>
    </div>
  </div>
</template>
<script>
import { saveOrder, submitOrder, getDetail, getAmount, getDealerAccountType, getDealerAddress } from '@/api/dealerSale/OrderManagement/OrderSubmissionSideB/index.js';
import { dictionary } from '@/utils/dictMixin';
import Cookies from 'js-cookie';
import selectCar from './selectCar';
import moment from 'moment';
export default {
  props: ['rowData'],
  data() {
    this.saveData = null;
    this.Amount = null;
    this.singleRebateFuelTotalAmount = null;
    this.buildRebateFuelTotalAmount = null;
    this.singleRebateEnergyTotalAmount = null;
    this.buildRebateEnergyTotalAmount = null;
    return {
      formList: this.createdFrom(),
      columns: this.createdTable(),
      tableList: [],
      dealerAddress: [],
      dealerAddressItemList: [],
      accountTypeList: [],
      isaddCar: false,
      dealerData: {},
      dealerCode: Cookies.get('ownerCode'),
      ischange: false
    };
  },
  components: {
    selectCar
  },
 async created() {
    this.getDealerAddress();
    this.getAmount();
    await this.getDealerAccountType();
    await this.init();
  },
  mounted() {
    this.table = this.$refs.table.$refs.pageTable;
  },
  mixins: [dictionary],
  methods: {
    createdFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '订单信息'
        },

        {
          type: 'INPUT',
          label: '订单编号',
          fieldName: 'orderNo',
          disabled: true
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearAndMonth',
          disabled: true,
          dateType: 'month'
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          placeholder: '请选择',
          itemList: this.createDictList('2105'),
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
          // ,
          // change: p => {
          //   this.changeFrom();
          // }
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          disabled: true,
          itemList: this.createDictList('2417')
         },
         {
          type: 'SELECT',
          label: '订单紧急度',
          fieldName: 'emergencyType',
          placeholder: '请选择',
          itemList: this.createDictList('2101'),
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
         {
          type: 'INPUT',
          label: '出资方',
          fieldName: 'majorCustomerName',
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'transportType',
          placeholder: '请选择',
          itemList: this.createDictList('2409'),
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '收车地址',
          fieldName: 'addressId',
          placeholder: '请选择',
          itemList: [],
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          change: (value) => {
            this.changeDealerAddress(value)
          },
        },
        {
          type: 'INPUT',
          label: '送达城市',
          fieldName: 'deliveryCityName',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'linkMan',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '联系电话',
          fieldName: 'linkPhone',
          disabled: true
        },
         {
          type: 'INPUT_NUMBER',
          precision: 2,
          initialValue: 0.0,
          label: '资金总余额',
          fieldName: 'totalAmount',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          initialValue: 0.0,
          label: '返利池可用余额',
          fieldName: 'rebateAmount',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '创建人',
          fieldName: 'createdName',
          disabled: true
        },
         {
          type: 'DATE',
          label: '创建时间',
          fieldName: 'createdAt',
          disabled: true,
          dateType: 'datetime'
        },
        
        {
          type: 'BREAK_SPACE',
          label: '车辆信息'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 120,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          }
        },

        {
          title: '物料编号',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          align: 'center',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '数量',
          dataIndex: 'orderNum',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'number',
          width: 100,
          editRequired: true,
          editPattern: /^[1-9]\d*$/,
          defaultEditable: true,
          rules: [{ required: true, message: '请填写正整数', trigger: 'blur' }],
          onInput: (index, data) => {
            this.changeNum(index, data);
          }
        },
        {
          title: '车辆用途',
          dataIndex: 'vehicleUse',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: p => {
            return (
              <el-select
            size="mini"
            v-model={p.row.vehicleUse}
            placeholder="请选择"
            onChange={value => {
              p.row.vehicleUse = value;
            }}
          >
            {this.createDictList('2416').map(item => (
              <el-option key={item.value} label={item.text} value={item.value} />
            ))}
          </el-select>
          );
          }
        },
        {
          title: '资金类型',
          dataIndex: 'accountId',
          sorter: true,
          filter: true,
          filterType: 'input',
          disabled: true,
          render: p => {
            return (
            <el-select size="mini" 
            v-model={p.row.accountId} 
            required placeholder="请选择"
            onChange={value => {p.row.accountId = value;}}>
            {p.row.accountTypeList.map(
              item => (<el-option key={item.accountId} label={item.accountTypeName} value={item.accountId} />
              ))}
            </el-select>
            );
            }
        },
        {
          title: '市场指导价',
          dataIndex: 'singleAmount',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'input'
        },
        {
          title: '车系名称',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
         {
          title: '配置',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '装配',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰',
          dataIndex: 'trimColorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    async init() {
      let res = await getDetail({ orderId: this.rowData.orderId });
      
      if (res.resultCode == 200) {
          for (let i in this.rowData) {
            this.formList.map((x) => {
              if (x.fieldName == i) {
                x.initialValue = this.rowData[i];
              }
            });
          }
          this.changeDealerAddress(this.rowData.addressId);
          this.tableList = res.data.detailDTOList;
          this.tableList.map(car => {
            //资金类型   
            car.accountTypeList = this.accountTypeList;
          });
          console.log('表格数据',this.tableList);
      }
    },
    //数字处理
    changeValueNum(a) {
      if (!a || a == null || isNaN(a)) {
        return 0;
      } else {
        return a;
      }
    },
    // 新增车辆
    addHandle() {
      this.$refs.from.SUBMIT_FORM();
      if (this.saveData) {
        let json = JSON.parse(JSON.stringify(this.saveData));
        json.dealerCode = this.dealerCode;
        this.dealerData = json;
        this.isaddCar = true;
        this.saveData = null;
      }
    },
    // async changeFrom() {
    //   if (this.tableList.length < 1) {
    //     return;
    //   }
    //   this.$refs.from.SUBMIT_FORM();
    //   if (this.saveData) {
    //     console.log('changeFrom', this.tableList);
    //     this.ischange = false;
    //   }
    // },
    changeHandle(val) {
      this.saveData = val;
    },
    //获取经销商收车地址
    async getDealerAddress() {
      let res = await getDealerAddress();
      this.dealerAddress = res.data;
      this.dealerAddressItemList =this.dealerAddress.map(x => (
        {
          text: `${x.address}${x.addressProperty == 60351001 ? '(主店)' : ''}`,
          value: x.addressId,
          addressProperty: x.addressProperty
        }
      ));
      console.log( this.dealerAddressItemList,'收车地址');
      this.formList.find(x => x.fieldName == 'addressId').itemList = this.dealerAddressItemList;
    },
    //修改收车地址
    changeDealerAddress(value) {
      for (let address of this.dealerAddress) {
        if(address.addressId == value) {
          this.formList[10].initialValue = address.cityName;
          this.formList[11].initialValue = address.linkMan;
          this.formList[12].initialValue = address.linkPhone;
          return;
        }
      }
    },
    //获取经销商可用资金总额和返利总额
    async getAmount(code) {
      let res = await getAmount();
      this.formList[13].initialValue = res.data.totalAmount;
      this.formList[14].initialValue = res.data.rebateAmount;
    },
    async getDealerAccountType() {
      let res = await getDealerAccountType();
      this.accountTypeList = res.data;
    },
    async closeDrawer(type) {
      if (type == 1) {
        //关闭
        this.$emit('close');
      } else if (type == 2) {
        //提交
        let submitData = this.buildSaveOrSubmitData();
        console.log('提交数据',submitData);
         let res = await submitOrder(submitData);
          if (res.resultCode == 200) {
            this.$notify({
              title: '成功',
              message: '提交成功',
              type: 'success'
            });
            this.$emit('close', submitData);
          } else {
            this.saveData = null;
          } 
      } else {
        //保存
        let savedata = this.buildSaveOrSubmitData();
        console.log('保存数据',savedata); 
         let res = await saveOrder(savedata);
          if (res.resultCode == 200) {
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success'
            });
            this.$emit('close', savedata);
          } else {
            this.saveData = null;
          }
      }
    },
    buildSaveOrSubmitData() {
      if (this.tableList.length < 1) {
          this.$notify({
            title: '警告',
            message: '请选择车辆',
            type: 'warning'
          });
          return;
        }
        this.$refs.from.SUBMIT_FORM();
        if (this.saveData) {
          let json = JSON.parse(JSON.stringify(this.saveData));
          let orderItem = this.tableList;
          let is = false;
          let orderTotalNum = 0;
          orderItem.map(x => {
            if (Number(x.orderNum) > 10000000000 || Number(x.orderNum) < 1) {
              is = true;
            }
            orderTotalNum = Number(orderTotalNum) + Number(x.orderNum);
          });
          if (is) {
            this.$notify({
              title: '警告',
              message: '输入数量过大或过小',
              type: 'warning'
            });
            return;
          }
          json.orderId = this.rowData.orderId;
          json.detailDTOList = orderItem;
          json.orderTotalNum = orderTotalNum;
          json.address = this.dealerAddress.find(x => json.addressId == x.addressId).address;
          json.orderYear = json.orderYearAndMonth.split('-')[0];
          json.orderMonth = json.orderYearAndMonth.split('-')[1];
          return json;
        }
    },
    async carcloseHandler(carList, dealerData) {
      this.isaddCar = false;
      this.saveData = null;
      console.log(carList,'选择车辆');
      carList.forEach(car => {
        //资金类型   
        car.accountTypeList = this.accountTypeList;
        // 提报数量
        car.orderNum = 1;
        // 车辆用途：默认客户订购
        car.vehicleUse = 24161001;
        // 资金类型：默认首项
        car.accountId = this.accountTypeList[0].accountId;
        // 市场指导价
        car.singleAmount = car.oemDirectivePrice;
      
        this.table.EXECUTE_INSERT([car]);
      });
    },
    // //校验当前可用资金是否足够支付选中物料
    // checkmoney(orderMain, orderitems) {
    //   let useRebateTotalAmount = 0;
    //   let useTotalAmount = 0;
      
    //   orderitems.map(x => {
    //     if(x.isRebate == 10041001) {
    //       useRebateTotalAmount = this.formatNumber(x.singleAmount) * x.orderNum + Number(useRebateTotalAmount);
    //     } else {
    //       useTotalAmount = this.formatNumber(x.singleAmount) * x.orderNum + Number(useTotalAmount);
    //     }
    //   });
    //   console.log('使用返利',useRebateTotalAmount);
    //   console.log('总支付',useTotalAmount);
    //   if(useRebateTotalAmount > orderMain.rebateAmount || useTotalAmount > orderMain.totalAmount) {
    //     return true;
    //   } else {
    //     return false;
    //   }
    // },
    //改变数量
    changeNum(index, data) {
      console.log(index, data, '改变数量');
      let num = '';
      let str = '';
      for (let i in index) {
        num = index[i];
        console.log(i, 'i');
        str = i.split('|')[0];
      }
      let Rep = /^[1-9]\d*$/;
      if (num > 10000000000) {
        this.$notify({
          title: '警告',
          message: '输入数量过大',
          type: 'warning'
        });
        return;
      }
      console.log(num, Rep.test(num));
    },
    async editHandle(data) {
      await this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.table.EXECUTE_DELETE([data]);
          console.log(this.tableList, '删除了');
        })
        .catch(() => {});
    },
    formatNumber(val) {
      return Number(val).toFixed(2);
    }
  }
};
</script>
<style lang="less">
.discount {
  text-decoration: underline;
  color: #d1291a;
  cursor: pointer;
}
</style>
